import { Core } from "@/comm/Core";
import { URL_KLINE_DATA, URL_KLINE_SYMBOL, URL_RECOMMEND_LIST,URL_COIN_STATE } from "@/comm/api";
import { toChartData } from "@/comm/format";
import { post, get } from "@/comm/request";
import { defineStore } from "pinia";

export interface CoinType {
	id: number;
	imageUrl: string;
	intervals: any[];
	show: boolean;
	symbol: string;
	tokenAddress: string;
	priceDisplayDp: number;
	sizeDisplayDp: number;
	priceChangePercent: number;
	lastPrice: number;
	quoteVolume: number;
	baseCurrency: string;
	quoteCurrency: string;
	[key: string]: any;
}

interface IState {
	map: Array<CoinType>;
	curCoin: CoinType;
	curInterval: IInterval;
	list: any[];
	lastCoin: CoinType;
	lastInterval: IInterval;
	linkVisible: boolean;
	TableRecommend: boolean;
	priceLen: number;
	recommendations: any[];
	tradingViewTime: any[];
	recommendationLoading: boolean;
	hasRed: boolean;
}

export interface IInterval {
	name: string;
	description: string;
	type: number;
}

let timer = 0;
export const useKline = defineStore("kline", {
	state: (): IState => ({
		map: [],
		curCoin: null as any,
		curInterval: null as any,
		list: [] as any[],
		lastCoin: null as any,
		lastInterval: null as any,
		linkVisible: false,
		TableRecommend: false,
		priceLen: 2,
		recommendations: [],
		recommendationLoading: false,
		tradingViewTime:[],
		hasRed: false,
	}),

	getters: {
		param(state) {
			return {
				symbol: state.curCoin?.symbol,
				interval: state.curInterval?.name || "S1"
			};
		}
	},
	actions: {
		async init() {
			// console.log("加载币对信息");
			const res: any = await get(URL_KLINE_SYMBOL);
			// console.log(res);
			this.map = res.data;
			await this.getBTCInfo()
			console.log('币对信息！！！！！！！！！！！！！！！！！！！！！！！！！！！！', this.map)
			// this.changeCurCoin(this.map[0]);
			this.readPrice();
			setInterval(() => { this.savePrice() }, 20000);
		},
		//获取BTC信息
		async getBTCInfo(){
			const res: any = await get(URL_COIN_STATE,{key:'BTCUSDT'});
			console.log('BTC信息',res)
			if(res.data){
				let obj = this.map.find(i=>i.symbol == 'BTCUSDT')
				if(obj){
					obj.lastPrice = res.data.c
					obj.quoteVolume = res.data.v
					obj.priceChangePercent = res.data.P
				}
			}
		},
		savePrice() {
			// console.log("savePrice")
			let PQ = this.map.map(i => {
				return {
					id: i.id,
					lastPrice: i.lastPrice,
					quoteVolume: i.quoteVolume,
					priceChangePercent: i.priceChangePercent
				}
			});
			localStorage.setItem("PQ", JSON.stringify(PQ));
		},
		readPrice() {
			let str = localStorage.getItem("PQ");
			// console.log("readPrice")
			if (str) {
				let PQ: Array<CoinType> = JSON.parse(str);
				this.map.forEach(i => {
					let item = PQ.find(t => i.id == t.id);
					if (item) {
						i.lastPrice = item.lastPrice;
						i.quoteVolume = item.quoteVolume;
						i.priceChangePercent = item.priceChangePercent;
					}
				})
			}
		},
		saveLastData() {
			console.log("##jsz", "保存币对信息");
			this.lastCoin = this.curCoin;
			this.lastInterval = this.curInterval;
		},
		readLastData() {
			console.log("##jsz", "读取币对信息");
			if (this.lastCoin) {
				this.curCoin = this.lastCoin;
			}
			if (this.lastInterval) {
				this.curInterval = this.lastInterval;
			}
		},
		getCoinByName(val: string) {
			let item = this.map.find(i => i.symbol == val);
			return item;
		},
		// 格式化周期适配tradingView
		formatTime(data:any){
			this.tradingViewTime= data.map((item:any)=>{
				 if(item.type!=0){
					if(item.type==1){
						return item.name.replace('MN','')
					}else{
						return item.name.split('').reverse().join("")
					}
				}
			}).filter(Boolean)
		},
		changeCurCoin(val: CoinType) {
			console.log("切换币种");
			this.curCoin = val;
			let timeType = location.pathname.includes("/coin") ? "K_TIME_COIN" : "K_TIME";
			let t = localStorage.getItem(timeType);
			console.log("##" + location.pathname)
			if (t) {
				let item = val.intervals.find(i => i.name == t);
				if (item) {
					this.changeCurInterval(item);
					return;
				}
			} else {
				if (this.curInterval) {
					let item = val.intervals.find(i => i.name == this.curInterval.name);
					if (item) {
						this.changeCurInterval(item);
						return;
					}
				}
			}

			this.changeCurInterval(val.intervals[0]);
			console.log("初始化111", val);
			// this.changeCurInterval(this.curInterval || val.intervals[0]);
		},
		changeCurCoinByName(val: string) {
			let item = this.map.find(i => i.symbol == val);
			if (item) {
				this.changeCurCoin(item);
			} else {
				this.changeCurCoin(this.map[0]);
			}
		},
		changeCurInterval(val: any) {
			this.curInterval = val;
			// this.recommendations = [];
			console.log("切换币种时间间隔", val);
		},
		changeCoinToDay(name: string,intervals:string) {
			console.log("jsz", "更换币种" + name);
			let item = this.map.find(i => i.symbol == name);
			if (item) {
				this.curCoin = item;
				this.curInterval = item.intervals.find(i => i.name == intervals);
			}
		},
		changePriceLen(val: number) {
			this.priceLen = val;
		},
		async loadHistory() {
			this.list = [];
			let url = URL_KLINE_DATA.replace("@", this.curCoin.symbol);
			let param = { interval: this.curInterval.name, limit: 1000 };
			let res: any = await get(url, param).catch(err => {
				return {};
			});
			// console.log("我是历史2",param)

			if (!res.data) {
				this.list = [];
			} else {
				this.list = res.data.map((item: any) => {
					return toChartData(item);
				});
			}
		},
		async loadMore(time: number, limit: number) {
			let url = URL_KLINE_DATA.replace("@", this.curCoin.symbol);
			let param = { interval: this.curInterval.name, endTime: time, limit };
			let res: any = await get(url, param).catch(err => {
				return {};
			});
			if (!res.data) {
				return [];
			}
			return res.data.map((item: any) => {
				return toChartData(item);
			});
		},
		changeLinkVisible(val: boolean) {
			this.linkVisible = val;
		},
		chilageTableRecommend(val: boolean) {
			this.TableRecommend = val;
		},
		async getRecommendations(clear = true) {
			if (timer) {
				window.clearInterval(timer);
			}
			// this.recommendationLoading = true;
			if (clear) {
				this.recommendationLoading = true;
				// this.recommendations = [];
			}
			if (this.curInterval.name == "S1") return;
			let res: any = await get(URL_RECOMMEND_LIST, { type: this.curInterval.name, last: true });
			console.log(this.curInterval.name, "this.curInterval.name");
			if (res.success) {
				this.recommendations = res.data;
			} else {
				this.recommendations = [];
			}
			console.log("isRedDot", Core.ins.isRedDot("DATE_RECOMMEND"))
			// if(Core.ins.isRedDot("DATE_RECOMMEND"))
			if(this.recommendations.length && Core.ins.isRedDot("DATE_RECOMMEND"))
			{
				this.hasRed = true;
			}
			this.recommendationLoading = false;
			timer = window.setInterval(() => {
				this.getRecommendations(false);
			}, 10000);
		}
	}
});
